Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
96.09% covered (success)
96.09%
123 / 128
50.00% covered (danger)
50.00%
2 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApieServiceProvider
96.09% covered (success)
96.09%
123 / 128
50.00% covered (danger)
50.00%
2 / 4
26
0.00% covered (danger)
0.00%
0 / 1
 autoTagHashmapActions
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
4.00
 boot
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
4
 register
94.37% covered (success)
94.37%
67 / 71
0.00% covered (danger)
0.00%
0 / 1
14.04
 sanitizeConfig
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2namespace Apie\LaravelApie;
3
4use Apie\AiInstructor\AiInstructorServiceProvider;
5use Apie\ApieCommonPlugin\ApieCommonPluginServiceProvider;
6use Apie\CmsApiDropdownOption\CmsDropdownServiceProvider;
7use Apie\Common\CommonServiceProvider;
8use Apie\Common\ContextBuilders\FrameworkContextBuilder;
9use Apie\Common\Interfaces\BoundedContextSelection;
10use Apie\Common\Interfaces\DashboardContentFactoryInterface;
11use Apie\Common\Wrappers\BoundedContextHashmapFactory;
12use Apie\Common\Wrappers\ConsoleCommandFactory as CommonConsoleCommandFactory;
13use Apie\Console\ConsoleServiceProvider;
14use Apie\Core\CoreServiceProvider;
15use Apie\Core\Session\CsrfTokenProvider;
16use Apie\DoctrineEntityConverter\DoctrineEntityConverterProvider;
17use Apie\DoctrineEntityDatalayer\Commands\ApieUpdateIdfCommand;
18use Apie\DoctrineEntityDatalayer\DoctrineEntityDatalayerServiceProvider;
19use Apie\DoctrineEntityDatalayer\EntityReindexer;
20use Apie\DoctrineEntityDatalayer\IndexStrategy\BackgroundIndexStrategy;
21use Apie\DoctrineEntityDatalayer\IndexStrategy\DirectIndexStrategy;
22use Apie\DoctrineEntityDatalayer\IndexStrategy\IndexAfterResponseIsSentStrategy;
23use Apie\DoctrineEntityDatalayer\IndexStrategy\IndexStrategyInterface;
24use Apie\Faker\FakerServiceProvider;
25use Apie\HtmlBuilders\ErrorHandler\CmsErrorRenderer;
26use Apie\HtmlBuilders\HtmlBuilderServiceProvider;
27use Apie\LaravelApie\Config\LaravelConfiguration;
28use Apie\LaravelApie\ContextBuilders\CsrfTokenContextBuilder;
29use Apie\LaravelApie\ContextBuilders\RegisterBoundedContextActionContextBuilder;
30use Apie\LaravelApie\ContextBuilders\SessionContextBuilder;
31use Apie\LaravelApie\ErrorHandler\ApieErrorRenderer;
32use Apie\LaravelApie\ErrorHandler\Handler;
33use Apie\LaravelApie\Providers\CmsServiceProvider;
34use Apie\LaravelApie\Providers\SecurityServiceProvider;
35use Apie\LaravelApie\Wrappers\Cms\DashboardContentFactory;
36use Apie\LaravelApie\Wrappers\Core\BoundedContextSelected;
37use Apie\LaravelApie\Wrappers\Queue\BackgroundProcessPersistListener;
38use Apie\Maker\MakerServiceProvider;
39use Apie\McpServer\McpServerServiceProvider;
40use Apie\RestApi\RestApiServiceProvider;
41use Apie\SchemaGenerator\SchemaGeneratorServiceProvider;
42use Apie\Serializer\SerializerServiceProvider;
43use Apie\ServiceProviderGenerator\TagMap;
44use Apie\TypescriptClientBuilder\TypescriptClientBuilderServiceProvider;
45use Illuminate\Config\Repository;
46use Illuminate\Contracts\Debug\ExceptionHandler;
47use Illuminate\Contracts\Events\Dispatcher;
48use Illuminate\Support\ServiceProvider;
49use Psr\EventDispatcher\EventDispatcherInterface;
50use Psr\Http\Message\ServerRequestInterface;
51use Symfony\Component\Config\ConfigCache;
52use Symfony\Component\Config\Definition\Processor;
53use Symfony\Component\Config\Resource\ReflectionClassResource;
54use Symfony\Component\Console\Application;
55use Symfony\Component\EventDispatcher\EventDispatcher;
56use Symfony\Component\Lock\LockFactory;
57
58class ApieServiceProvider extends ServiceProvider
59{
60    /**
61     * @var array<string, array<int, class-string<ServiceProvider>>> $dependencies
62     */
63    private array $dependencies = [
64        'enable_ai_instructor' => [
65            AiInstructorServiceProvider::class,
66        ],
67        'enable_common_plugin' => [
68            ApieCommonPluginServiceProvider::class,
69        ],
70        'enable_cms' => [
71            CommonServiceProvider::class,
72            HtmlBuilderServiceProvider::class, // it's important that this loads before CmsServiceProvider!!!
73            CmsServiceProvider::class,
74            SerializerServiceProvider::class,
75        ],
76        'enable_cms_dropdown' => [
77            CommonServiceProvider::class,
78            CmsDropdownServiceProvider::class,
79        ],
80        'enable_core' => [
81            CoreServiceProvider::class,
82        ],
83        'enable_console' => [
84            CommonServiceProvider::class,
85            ConsoleServiceProvider::class,
86            SerializerServiceProvider::class,
87        ],
88        'enable_doctrine_entity_converter' => [
89            CoreServiceProvider::class,
90            DoctrineEntityConverterProvider::class,
91        ],
92        'enable_doctrine_entity_datalayer' => [
93            CoreServiceProvider::class,
94            DoctrineEntityConverterProvider::class,
95            DoctrineEntityDatalayerServiceProvider::class,
96        ],
97        'enable_security' => [
98            CommonServiceProvider::class,
99            SerializerServiceProvider::class,
100            SecurityServiceProvider::class,
101        ],
102        'enable_rest_api' => [
103            CommonServiceProvider::class,
104            RestApiServiceProvider::class,
105            SchemaGeneratorServiceProvider::class,
106            SerializerServiceProvider::class,
107        ],
108        'enable_faker' => [
109            FakerServiceProvider::class,
110        ],
111        'enable_maker' => [
112            MakerServiceProvider::class,
113        ],
114        'enable_mcp_server' => [
115            CommonServiceProvider::class,
116            SerializerServiceProvider::class,
117            McpServerServiceProvider::class,
118        ],
119        'enable_typescript_client_builder' => [
120            TypescriptClientBuilderServiceProvider::class,
121        ],
122    ];
123
124    private function autoTagHashmapActions(): void
125    {
126        $boundedContextConfig = config('apie.bounded_contexts');
127        $scanBoundedContextConfig = config('apie.scan_bounded_contexts');
128        $factory = new BoundedContextHashmapFactory(
129            $boundedContextConfig ?? [],
130            $scanBoundedContextConfig ?? [],
131            new EventDispatcher(),
132        );
133        $hashmap = $factory->create();
134        foreach ($hashmap as $boundedContext) {
135            foreach ($boundedContext->actions as $action) {
136                $class = $action->getDeclaringClass();
137                if (!$class->isInstantiable()) {
138                    continue;
139                }
140                $className = $class->name;
141                TagMap::register(
142                    $this->app,
143                    $className,
144                    ['apie.context']
145                );
146            }
147        }
148    }
149
150    public function boot(): void
151    {
152        $this->autoTagHashmapActions();
153        $this->loadViewsFrom(__DIR__ . '/../templates', 'apie');
154        $this->loadRoutesFrom(__DIR__.'/../resources/routes.php');
155        TagMap::registerEvents($this->app);
156
157        if ($this->app->runningInConsole()) {
158            $commands = [];
159            $commands[] = ApieUpdateIdfCommand::class;
160            // for some reason these are not called in integration tests without re-registering them
161            foreach (TagMap::getServiceIdsWithTag($this->app, 'console.command') as $taggedCommand) {
162                $serviceId = 'apie.console.tagged.' . $taggedCommand;
163                $this->app->singleton($serviceId, function () use ($taggedCommand) {
164                    return $this->app->get($taggedCommand);
165                });
166                $commands[] = $serviceId;
167            }
168            /** @var CommonConsoleCommandFactory $factory */
169            $factory = $this->app->get('apie.console.factory');
170            foreach ($factory->create($this->app->get(Application::class)) as $command) {
171                $serviceId = 'apie.console.registered.' . $command->getName();
172                $this->app->instance($serviceId, $command);
173                $commands[] = $serviceId;
174            }
175            $this->commands($commands);
176        }
177    }
178
179    public function register()
180    {
181        $this->mergeConfigFrom(__DIR__ . '/../resources/apie.php', 'apie');
182
183        $this->app->bind(FrameworkContextBuilder::class, function () {
184            return new FrameworkContextBuilder('laravel');
185        });
186        TagMap::register($this->app, FrameworkContextBuilder::class, ['apie.core.context_builder']);
187
188        // add PSR-14 support if needed:
189        if (!$this->app->bound(EventDispatcherInterface::class)) {
190            $this->app->bind(EventDispatcherInterface::class, function () {
191                return new class($this->app->make(Dispatcher::class)) implements EventDispatcherInterface {
192                    public function __construct(private readonly Dispatcher $dispatcher)
193                    {
194                    }
195
196                    public function dispatch(object $event): object
197                    {
198                        $this->dispatcher->dispatch($event);
199                        return $event;
200                    }
201                };
202            });
203        }
204
205        // fix for https://github.com/laravel/framework/issues/30415
206        $this->app->extend(
207            ServerRequestInterface::class,
208            function (ServerRequestInterface $psrRequest) {
209                $route = $this->app->make('request')->route();
210                if ($route) {
211                    $parameters = $route->parameters();
212                    foreach ($parameters as $key => $value) {
213                        $psrRequest = $psrRequest->withAttribute($key, $value);
214                    }
215                }
216                return $psrRequest;
217            }
218        );
219
220        $this->app->bind(IndexStrategyInterface::class, function () {
221            $config = config();
222            if ($config->get('apie.enable_doctrine_entity_datalayer')) {
223                $type = $config->get('apie.doctrine.indexing.type', 'direct');
224                return match ($type) {
225                    'direct' => new DirectIndexStrategy($this->app->get(EntityReindexer::class)),
226                    'late' => new IndexAfterResponseIsSentStrategy($this->app->get(EntityReindexer::class)),
227                    'background' => new BackgroundIndexStrategy(),
228                    default => $this->app->get(config('apie.doctrine.indexing.service', DirectIndexStrategy::class)),
229                };
230            }
231
232            return new DirectIndexStrategy($this->app->get(EntityReindexer::class));
233        });
234
235        $this->app->bind(ApieErrorRenderer::class, function () {
236            return new ApieErrorRenderer(
237                $this->app->bound(CmsErrorRenderer::class) ? $this->app->make(CmsErrorRenderer::class) : null,
238                $this->app->make(\Apie\Common\ErrorHandler\ApiErrorRenderer::class),
239                config('apie.cms.base_url')
240            );
241        });
242
243        $this->app->extend(ExceptionHandler::class, function (ExceptionHandler $service) {
244            return new Handler($this->app, $service);
245        });
246
247        $this->app->bind(LockFactory::class, function () {
248            $config = config('apie.lock_store');
249            return new LockFactory($this->app->get($config));
250        });
251        
252        $this->app->bind(DashboardContentFactoryInterface::class, DashboardContentFactory::class);
253        $this->app->bind(BoundedContextSelection::class, BoundedContextSelected::class);
254
255        $alreadyRegistered = [];
256        foreach ($this->dependencies as $configKey => $dependencies) {
257            if (config('apie.' . $configKey, false)) {
258                foreach ($dependencies as $dependency) {
259                    if (!isset($alreadyRegistered[$dependency])) {
260                        $alreadyRegistered[$dependency] = $dependency;
261                        $this->app->register($dependency);
262                    }
263                }
264            }
265        }
266        //$this->app->bind(CsrfTokenProvider::class, CsrfTokenContextBuilder::class);
267        TagMap::register($this->app, CsrfTokenContextBuilder::class, ['apie.core.context_builder']);
268        $this->app->tag(CsrfTokenContextBuilder::class, ['apie.core.context_builder']);
269
270        // this has to be added after CsrfTokenContextBuilder!
271        $this->app->bind(SessionContextBuilder::class);
272        TagMap::register($this->app, SessionContextBuilder::class, ['apie.core.context_builder']);
273        $this->app->tag(SessionContextBuilder::class, ['apie.core.context_builder']);
274
275        TagMap::register($this->app, RegisterBoundedContextActionContextBuilder::class, ['apie.core.context_builder']);
276        $this->app->tag(RegisterBoundedContextActionContextBuilder::class, ['apie.core.context_builder']);
277        $this->app->extend('config', function (Repository $config) {
278            $this->sanitizeConfig($config);
279        
280            return $config;
281        });
282
283        TagMap::register($this->app, BackgroundProcessPersistListener::class, ['kernel.event_subscriber']);
284    }
285
286    private function sanitizeConfig(Repository $config): void
287    {
288        $rawConfig = $config->get('apie');
289        $path = storage_path('framework/cache/apie-config' . md5(json_encode($rawConfig)) . '.php');
290        $resources = [
291            new ReflectionClassResource(new \ReflectionClass(LaravelConfiguration::class)),
292            new ReflectionClassResource(new \ReflectionClass(static::class)),
293        ];
294        $configCache = new ConfigCache($path, true);
295        if ($configCache->isFresh()) {
296            $processedConfig = require $path;
297        } else {
298            $configuration = new LaravelConfiguration();
299
300            $processor = new Processor();
301
302            $processedConfig = $processor->processConfiguration($configuration, ['apie' => $rawConfig]);
303
304            if (!isset($processedConfig['scan_bounded_contexts'])) {
305                $processedConfig['scan_bounded_contexts'] = [];
306            }
307            if (empty($processedConfig['storage'])) {
308                $processedConfig['storage'] = null;
309            }
310            $code = '<?php' . PHP_EOL . 'return ' . var_export($processedConfig, true) . ';';
311            $configCache->write($code, $resources);
312        }
313
314        $config->set('apie', $processedConfig);
315    }
316}